<?php
namespace Wechat\Controller;
use Think\Controller;
use Think\Page;

class MallController extends WechatController {
	//模板id
	public $tid = null;
	//商城的配置信息
	public $mallconfig = null;
	//模板信息
	public $template = null;
	/**
	 * 模板列表
	 * @date: 2014-11-25
	 * @author: 琴
	 * @return:
	 */
	protected function template(){
		//获取用户的微商城配置信息
		$MallConfigLogic = D('MallConfig','Logic');
		$mallconfig = $MallConfigLogic->detail();
		$tid = $mallconfig['template'];
		$this -> assign('tid',$tid);
		$this -> assign('mallconfig',$mallconfig);
		// 		$websiteconfig = null;
		// 		$WebsiteConfigLogic = null;
		//模板信息
		$MallTemlatesLogic = D('MallTemlates','Logic');
		$template = $MallTemlatesLogic -> detail($tid);
		if(!isset($template['id']) ||  empty($template)){
			$this -> error('当前模板不存在或者已经下架');
		}
		$this -> assign('template',$template);
		return $template;
	}
	/**
	 * object数组转成array数组
	 * */
	
	public function object_array($array) {
		if(is_object($array)) {
			$array = (array)$array;
		} if(is_array($array)) {
			foreach($array as $key => $value) {
				$array[$key] = $this -> object_array($value);
			}
		}
		return $array;
	}

	
	
	
	 /**
	 * 拼团首页
	 * @date: 2015-11-6
	 * @author: weixuan
	 * @return:
	 */
	public function index(){
		$productLogic = D('FightgroupProduct','Logic');
		
		if(IS_POST){
			$where['uid'] = WID;
			$where['ishidden'] = 0;
			$where['ispublish'] = 1;
			$count = $productLogic -> where($where) -> count();
			$page = new Page($count,2);
			$show = $page -> show();
			$product = $productLogic -> where($where) -> limit($page->firstRow.','.$page->listRows) -> select();
			if($product){
				//dump($product);
				$this -> ajaxReturn(array('ret' => 1,'msg' => $product));
			}else{
				$this -> ajaxReturn(array('ret' => 0));
			}
		}else{
			
			
			$this -> display();
		}

	}
	
	
	
	/**
	 * 产品详情页
	 * @date: 2015-11-6
	 * @author: weixuan
	 * @return:
	 */
	public function productdetail(){
		session('addressid',null);
		$productLogic = D('FightgroupProduct','Logic');
		$productGroupLogic = D('FightgroupProductgroup','Logic');
		$productSpecLogic = D('FightgroupProductspec','Logic');
		$groupLogic = D('FightgroupGroup','Logic');
		$groupLogLogic = D('FightgroupGrouplog','Logic');
		$userinfo = session('userinfo');
		$openid = $userinfo['openid'];
		if(IS_POST){
			//根据选择的成团人数选择不同价钱
			$nid = I('post.nid');
			if($nid){
				$price = $productGroupLogic -> where(array('id'=>$nid)) -> field('price') -> find();
				$this->ajaxReturn(array('ret' => 1,'msg' => $price));
			}
		
		}else{
			$id = I('get.id');
			$where = array(
					'uid'		=>WID,
					'id'		=>$id,
					'ishidden'	=>0,
					'ispublish' =>1,
			);
			$productList = $productLogic -> where($where) -> find();
			$productList['imgpath'] = serializeMysql($productList['imgpath'],1);	//产品轮播图片
			$this -> assign('data',$productList);
			//成团数
			$groupCount = $groupLogic -> where(array('uid' => WID,'productid' => $id,'ishidden' => 0,'status' => array('in','2,3,4'))) -> count();
			$this -> assign('count',$groupCount);
			
			//如果是点击链接进来参团，则只显示团长成团人数去参加
			$gid = I('get.g');
			if($gid){
				$group = $groupLogic -> where(array('uid' => WID,'id' => $gid,'ishidden' => 0)) -> find();
				session('gid',$gid);
				
				$groupLog=$groupLogLogic-> where(array('uid' => WID,'openid' => $openid,'groupid' => $gid,'ishidden' => 0)) -> find();
				if($groupLog){
					$group['jion']=1;
				}
				$this -> assign('group',$group);
				
			}else{
				session('gid',null);
			}
			//显示该产品的成团人数
			$productGroup = $productGroupLogic -> where(array('uid' => WID,'productid' => $id,'ishidden' => 0)) -> select();
			$this -> assign('productgroup',$productGroup);
			//商品规格
			$productSpec = $productSpecLogic -> where(array('uid' => WID,'productid' => $id,'ishidden' => 0)) -> select();
			$this -> assign('spec',$productSpec);
			
			$this -> display();
		}
		
		
	}
	/**
	 * 规则
	 * @date: 2015-11-6
	 * @author: weixuan
	 * @return:
	 */
	public function rule(){
		$processLogic = D('FightgroupProcess','Logic');
		$process = $processLogic -> where(array('uid' => WID)) -> find();
		$this -> assign('data',$process);
		$this -> display();
	}
	/**
	 * 保存订单数据
	 * @date: 2015-11-9
	 * @author: weixuan
	 * @return:
	 */
	public function goorder(){
		if(I('post.addressid')){
			$addressid = I('post.addressid');
			session('addressid',$addressid);
		}else{
			$data = array(
					'sid'				=>I('post.sid'),
					'productgroupid'	=>I('post.productgroupid'),
					'num'				=>I('post.num'),
			);

			session('data',$data);
		}
		
		
		$this -> ajaxReturn(array('ret' => 1));
		

	}
	
	
	/**
	 * 订单
	 * @date: 2015-11-9
	 * @author: weixuan
	 * @return:
	 */
	public function order(){
		$gid = session('gid');
		$productLogic = D('FightgroupProduct','Logic');
		$productSpecLogic = D('FightgroupProductspec','Logic');
		$productGroupLogic = D('FightgroupProductgroup','Logic');
		$addressLogic = D('FightgroupAddress','Logic');	
		$sid = session('data')['sid'];
		$productSpec = $productSpecLogic -> where(array('uid' => WID,'id' => $sid,'ishidden' => 0)) -> find();
		$this -> assign('spec',$productSpec);
		session('productSpec',$productSpec);
		 $where = array(
				'uid'		=>WID,
				'id'		=>$productSpec['productid'],
				'ishidden'	=>0,
				'ispublish' =>1,
		); 
		$product = $productLogic -> where($where) -> find();
		$product['num'] = session('data')['num'];
		
		$productGroup = $productGroupLogic -> where(array('uid' => WID,'id' => session('data')['productgroupid'],'ishidden' => 0)) -> find();
		session('productGroup',$productGroup);
		$product['price'] = $productGroup['price'];
		$product['totalprice'] = floatval($product['price'])*intval($product['num']);
		session('product',$product);
		$this -> assign('product',$product);
		//地址
		//session('addressid',null);
		$addressid = session('addressid');
		if($addressid){
			$address = $addressLogic -> where(array('uid' => WID,'id' => $addressid)) -> find();
			session('address',$address);
			$this -> assign('address',$address);
		}else{
			//默认地址
			$userinfo = session('userinfo');
			$openid = $userinfo['openid'];
			$address = $addressLogic -> where(array('uid' => WID,'openid' => $openid,'ishidden' => 0,'isdefault' => 1)) -> find();
			session('address',$address);
			$this -> assign('address',$address);
		}

		$this -> display();
	}
	/**
	 * 下订单
	 * @date: 2015-11-9
	 * @author: weixuan
	 * @return:
	 */
	public function doorder(){
		$groupLogic = D('FightgroupGroup','Logic');
		$processLogic = D('FightgroupProcess','Logic');
		$groupLogLogic = D('FightgroupGrouplog','Logic');
		$orderLogic = D('FightgroupOrder','Logic');
		$userinfo = session('userinfo');
		$openid = $userinfo['openid'];
		//区分团长和团员
		$gid = session('gid');
		//订单编号
		$ordernumber = $this -> createnumber();
		//成团信息添加（团长需添加，团员只要在hasjon+1）
		$productGroup = session('productGroup');
		
		$groupData = array(
				'uid'				=>WID,
				'productid' 		=> $productGroup['productid'],
				'productgroupid'	=>$productGroup['id'],
				'groupnumber'		=>$productGroup['groupnumber'],
				'hasjoin' 			=>1,
				//'createtime'		=>time(),
				'price'				=>$productGroup['price'],
				'status'			=>7,
				//'period'			=>'',
				'isexpired'			=>0,
				'ishidden'			=>0,
		);
		/* $process = $processLogic -> where(array('uid' => WID)) -> field('expiredtime') -> find();
		if($process['expiredtime']==0){
			$groupData['period'] = 0;
		}else{
			$groupData['period'] = $process['expiredtime']*3600+time();
		} */
		if($gid){
			//支付后修改
			//$ret1 = $groupLogic -> where(array('uid' => WID,'id' => $gid,'ishidden' => 0)) -> setInc('hasjoin');
			$ret1 = $gid;
		}else{
			$ret1 = $groupLogic -> add($groupData);
		}
		
		//成团个人详情添加
		$product = session('product');
	 	$groupLogData = array(
				'uid'				=>WID,
				'openid' 			=>$openid,
				'nickname'			=>$userinfo['nickname'],
				'productid' 		=> $productGroup['productid'],
				'productcoverimg'	=>$product['coverimg'],
				'productgroupid'	=>$productGroup['id'],
				'productname'		=>$product['name'],
				'productprice'		=>$productGroup['price'],
	 			'headimgurl'		=>$userinfo['headimgurl'],	
				'groupnumber'		=>$productGroup['groupnumber'],
	 			'ordernumber'		=>$ordernumber,
				//'createtime'		=>time(),
	 			//'period'			=>$groupData['period'],
				'isexpired'			=>0,
				'ishidden'			=>0,
		); 
	 	if($gid){
	 		$groupLogData['groupid'] = $gid;
	 		$groupLogData['isleader'] = 0;
	 	}else{
	 		$groupLogData['groupid'] = $ret1;
	 		$groupLogData['isleader'] = 1;
	 	}
	 	$ret2=$groupLogLogic -> add($groupLogData);
	 	//添加订单信息
	 	$productSpec = session('productSpec');
	 	$address = session('address');
	 	$orderData = array(
	 			'uid'				=>WID,
	 			'ordernumber'		=>$ordernumber,
	 			'openid' 			=>$openid,	 			
	 			'nickname'			=>$userinfo['nickname'],
	 			'groupid'			=>$groupLogData['groupid'],
	 			'productid' 		=> $productGroup['productid'],
	 			'procudtspecid'		=>$productSpec['id'],
	 			'procudtspec'		=>$product['spec'],
	 			'coverimg'			=>$product['coverimg'],
	 			'spectype'			=>$productSpec['spectype'],
	 			'productgroupid'	=>$productGroup['id'],
	 			'productgroupnumber'=>$productGroup['groupnumber'],
	 			'buynumber'			=>session('data')['num'],
	 			'productname'		=>$product['name'],
	 			
	 			'price'				=>$productGroup['price'],
	 			'totalprice'		=>floatval($productGroup['price'])*intval(session('data')['num']),
	 			'remark'			=>I('post.remark'),
	 			'addressid'			=>$address['id'],
	 			'createtime'		=>time(),
	 			'ispay'				=>0,
	 			'status'			=>1,
	 			'ishidden'			=>0,
	 	);
	 	if($gid){
	 		$orderData['isleader'] = 0;
	 	}else{
	 		$orderData['isleader'] = 1;
	 	}
	 	$ret3 = $orderLogic -> add($orderData);
	 	if($ret1&&$ret2&&$ret3){
	 		$this -> ajaxReturn(array('ret' => 1,'id' => $ret3));
	 	}
		
	}
	
	/**
	 * 地址列表
	 * @date: 2015-11-9
	 * @author: weixuan
	 * @return:
	 */
	public function address(){
		$addressLogic = D('FightgroupAddress','Logic');
		$userinfo = session('userinfo');
		$openid = $userinfo['openid'];
		$address = $addressLogic -> where(array('uid' => WID,'openid' => $openid,'ishidden' => 0)) -> select();
		$this -> assign('list',$address);
		$this -> display();
	}
	
	/**
	 * 收货地址编辑、添加页面显示
	 * @date: 2015-11-6
	 * @author: 陈雄华
	 * @return:
	 */
	public function addressedit(){
		$addressLogic = D('FightgroupAddress','Logic');
		if(IS_POST){
			//用户信息
			$userinfo = session('userinfo');
			$openid = $userinfo['openid'];
			$nickname = $userinfo['nickname'];
			
			$id = I('post.id');
			$linktel = I('post.linktel');
			$isdefault = I('post.isdefault');
			//判断电话号码格式是否正确，错误则返回提示信息
			if(preg_match("/1[3458]{1}\d{9}$/",$linktel)){
				$linktel = $linktel;
			}else{
				$this -> ajaxReturn ( array (
						'ret' => 2,
						'msg' => '手机号码格式不正确',
				) );
			}
			
			//post过来的数据信息
			$where = array(
					'uid'   		=>WID,
					'openid' 		=> $openid,
					'nickname' 		=> $nickname,
					'linkman' 		=> I('post.linkman'),
					'linktel' 		=> $linktel,
					'area' 			=> I('post.area'),
					'address' 		=> I('post.address'),
					'createtime' 	=> time(),
					'isdefault'		=> $isdefault,
			);
			if($isdefault == 1){
				//查找是否已经有了默认地址
				$address=$addressLogic -> where(array('uid' => WID,'openid' => $openid, 'isdefault' => 1)) -> field('id') -> find();
				if($address['id'] == ''){
					$res = $addressLogic -> add($where);
				}else{
					$addressLogic -> where(array('uid' => WID,'id' => $address['id'])) -> save(array('isdefault' => 0));
					$res = $addressLogic -> add($where);
				}
			}else{
				$res = $addressLogic -> add($where);
			}
				
			//判断操作是否成功
			if($res){
				$this->ajaxReturn(array('ret' => 1, 'msg' => '添加成功'));
			}else{
				$this->ajaxReturn(array('ret' => 2, 'msg' => '添加失败'));
			}
			
			
		}
		$this -> display();
	}
	/**
	 * 生成订单随机编号
	 * @date: 2015-7-8
	 * @author: 魏暄
	 * @return:
	 */
	public function createnumber(){
		$orderLogic = D('FightgroupOrder','Logic');
		//$orderList = $orderLogic ->select();
		$number = date('Ymd');
		for ($i = 0;$i<6;$i++){
			$number .= rand(0, 9);
		}
		$res = $orderLogic -> where(array('ordernumber' => $number)) -> find();   //保证生成的订单编号不会重复
		if($res){
			$this -> createNumber();
		}else{
			return $number;
		}
	}
	/**
	 * 确认订单
	 * @date: 2015-11-10
	 * @author: weixuan
	 * @return:
	 */
	public function orderdetail(){
		session('addressid',null);
		$orderLogic = D('FightgroupOrder','Logic');
		$addressLogic = D('FightgroupAddress','Logic');
		$orderId = I('get.id');
		$order = $orderLogic -> where(array('uid' => WID,'id' => $orderId)) -> find();
		$address = $addressLogic -> where(array('uid' => WID,'id' => $order['addressid'])) -> find();
		$order['area'] = $address['area'];
		$order['address'] = $address['address'];
		$order['linkman'] = $address['linkman'];
		$order['linktel'] = $address['linktel'];
		$this -> assign('order',$order);
		$this -> display();
	}
	/**
	 * 支付订单
	 * @date: 2015-11-10
	 * @author: 魏暄
	 * @return:
	 */
	public function orderpay(){
		$orderLogic = D('FightgroupOrder','Logic');
	
		$orderid = I('post.id');
		$order = $orderLogic -> where(array('uid' => WID,'id' => $orderid)) -> find();
	
		if($order){
	
			$ordersn = $order['ordernumber'];
			$MallpayLogic = D('MallPay','Logic');
			$mallpay = $MallpayLogic -> where(array('uid' => WID)) -> find();
			$mallpay = serializeMysql($mallpay['configs'],1);
			$userconfiginfo = session('userconfiginfo');
			$price = $order['totalprice']*100;
			$dealarr = array(
					'out_trade_no' 	=> $ordersn,
					//'total_fee' => $price,
					'total_fee' 	=> 1,
					'appid' 		=> $userconfiginfo['appid'],
					'appsecret'		=> $userconfiginfo['appsecret'],
					'body' 			=> '拼团',
					'mch_id' 		=> $mallpay['wxpay']['mchid'],
					'partnerkey' 	=>	$mallpay['wxpay']['partnerkey'],
					'sslcert' 		=> '/zhifu/WxPayPubHelper/cacert/apiclient_cert.pem',
					'sslkey' 		=> '/zhifu/WxPayPubHelper/cacert/apiclient_key.pem',
					'notify_url' 	=> C('WEB_ABSOLUTE_URL').'/wechat.php/Mall/notify',
	
			);
			session('dealarr',$dealarr);
			$this -> ajaxReturn(array('ret' => 1));
			//$this -> ajaxReturn(array('ret'=>1));
		}else{
			$this -> ajaxReturn(array('ret' => 0,'msg' => '提交失败，请稍后再试'));
		}
	
	
	
	}
	/**
	 * 微信支付
	 * @date: 2015-3-17
	 * @author: 明
	 * @return:
	 */
	public function wxpay(){
		$dealarr = session('dealarr');
		$userinfo = session('userinfo');
		$wxpay = new WxpayController();
		$prepay_id = $wxpay->getPrepayId($userinfo['openid'],$dealarr);
		$jsApiParameters = $wxpay->getParameters($prepay_id);
		$this -> assign('jsApiParameters',$jsApiParameters);
	
		$this -> display();
	}
	/**
	 * 处理支付的反馈结果
	 * @date: 2015-11-12
	 * @author: 魏暄
	 * @return:
	 */
	public function notify(){
	
	
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		//dump($xml);
		$path = RUNTIME_PATH.'Logs/log1.log';
		$f = fopen($path, 'w');
		$file = fwrite($f, print_r($xml,true));
		$wxpay = new WxpayController();
		$data = $wxpay->xmlToArray($xml);
		$path = RUNTIME_PATH.'Logs/log2.log';
		$f = fopen($path, 'w');
		$file = fwrite($f, print_r($data,true));
		//本地签名验证
		$sign = $wxpay->checkSign($data);
		$returnParameters =array();
		if($sign == FALSE){
	
			$this->setReturnParameter("return_code","FAIL",$returnParameters);//返回状态码
	
			$this->setReturnParameter("return_msg","签名失败",$returnParameters);//返回信息
		}else{
			$this->setReturnParameter("return_code","SUCCESS",$returnParameters);//设置返回码
		}
		$returnXml = $wxpay->arrayToXml($returnParameters);
		echo $returnXml;
		$orderLogic = D('FightgroupOrder','Logic');
		$groupLogic = D('FightgroupGroup','Logic');
		$groupLogLogic = D('FightgroupGrouplog','Logic');
		$config = serialize($data);
		$savedata=array(
				'ispay' => 1,
				'status'=>2,
				//'config' => $config,
				//'paystatus'	=> 1,
		);
		//判断订单状态是否已经修改
		$orderinfo = $orderLogic->where(array('ordernumber'=>$data['out_trade_no']))->find();
		if($orderinfo['status'] != '2'){
			$res = $orderLogic->where(array('ordernumber'=>$data['out_trade_no']))->save($savedata);
			//存入订单日志
	
			$orderslogLogic = D('MallOrderslog','Logic');
			$log = array(
					'operator'	=> '系统',
					'detail'	=>'支付完成',
					'type'      => 'orderpay',
					'operatortype'	=> 3,
					'createtime'	=> time(),
					'orderid'		=> $orderinfo['id'],
			);
			//查找该订单是否已经有支付日志
			$map = array(
					'orderid' => $orderinfo['id'],
					'type' => 'orderpay'
			);
			$res = $orderslogLogic->where($map)->find();
			if(empty($res)){
				$orderslogLogic->add($log);
	
	
				//支付修改产品购买数
				$productLogic = D('FightgroupProduct','Logic');
				$productLogic -> where(array('uid' => $orderinfo['uid'],'id' => $orderinfo['productid'])) -> setInc('buynumber',$orderinfo['buynumber']);
				//支付修改产品库存数
				$productSpecLogic = D('FightgroupProductspec','Logic');
				$productSpecLogic -> where(array('uid' => $orderinfo['uid'],'id' => $orderinfo['procudtspecid'])) -> setDec('restnumber',$orderinfo['buynumber']);
				//支付修改成团状态
				$groupLogic = D('FightgroupGroup','Logic');
				//$groupLogic -> where(array('uid' => $orderinfo['uid'],'id' => $orderinfo['groupid'],'ishidden' => 0)) -> save(array('status'=>1));
				
			
				//判断是否满员
				$group=$groupLogic -> where(array('uid' => $orderinfo['uid'],'id' => $orderinfo['groupid'],'ishidden' => 0)) ->field('groupnumber,hasjoin,period') ->find();
				if($group['groupnumber'] == $group['hasjoin']){
					$groupLogic -> where(array('uid' => $orderinfo['uid'],'id' => $orderinfo['groupid'],'ishidden' => 0)) ->save(array('status'=>2));
				}
				
				//判断是否是团员
				if($orderinfo['isleader'] == '0'){
					//团员
					$groupLogic -> where(array('uid' => $orderinfo['uid'],'id' => $orderinfo['groupid'],'ishidden' => 0)) -> setInc('hasjoin');
					
					//修改grouplog里的到期时间
					//团员修改到期时间
					$groupLogData['createtime'] = time();
					$groupLogData['period']=$group['period'];
					$groupLogLogic -> where(array('uid' => $orderinfo['uid'],'openid' => $orderinfo['openid'],'groupid' => $orderinfo['groupid'],'ishidden' => 0)) -> save($groupLogData);
				}else{
					//修改成团到期时间和成团状态
					$processLogic = D('FightgroupProcess','Logic');
					$process = $processLogic -> where(array('uid' => $orderinfo['uid'])) -> field('expiredtime') -> find();
					if($process['expiredtime']==0){
						$groupData['period'] = 0;
					}else{
						$groupData['period'] = $process['expiredtime']*3600+time();
					}
					$groupData['createtime'] = time();
					$groupData['status'] = 1;
					$groupLogic -> where(array('uid' => $orderinfo['uid'],'id' => $orderinfo['groupid'],'ishidden' => 0)) -> save($groupData);
					//修改grouplog里的到期时间
					//团长到期时间
					$groupLogData['period']=$groupData['period'];
					$groupLogData['createtime'] = time();
					$groupLogLogic -> where(array('uid' => $orderinfo['uid'],'openid' => $orderinfo['openid'],'groupid' => $orderinfo['groupid'],'ishidden' => 0)) -> save($groupLogData);
				}
				
				
			}
	
		}
			
	}
	
	
	
	/**
	 * 支付成功
	 * @date: 2015-11-10
	 * @author: 魏暄
	 * @return:
	 */
	public function success(){
		$this -> display();
	}
}